package com.epoint.androidphone.mobileoa.ui.attachmanager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.Html;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.epoint.androidmobile.core.control.AlertUtil;
import com.epoint.androidmobile.core.control.ToastUtil;
import com.epoint.androidmobile.core.io.IOHelp;
import com.epoint.androidmobile.core.tools.Arithmetic;
import com.epoint.androidphone.R;
import com.epoint.androidphone.mobileoa.ui.init.InitView;
import com.epoint.androidphone.mobileoa.ui.superview.SuperPhonePage;

/**
 * @author liyc
 * @time 2013-5-9 上午10:48:14
 * @annomation 附件管理
 */
public class AttachManagerView extends SuperPhonePage {

	ListView lv;
	private List<Map<String, Object>> mData = new ArrayList<Map<String,Object>>();
	EditText etCondition;
	ImageView ivQuery;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addContentViewAndTitle(R.layout.attachmanagerview, getIntentViewTitle());
		lv = (ListView) findViewById(R.id.lv);
		lv.setOnItemClickListener(this);
		lv.setOnItemLongClickListener(this);
		etCondition = (EditText) findViewById(R.id.etCondition);
		ivQuery = (ImageView) findViewById(R.id.ivQuery);
		ivQuery.setOnClickListener(this);
		IOHelp.FoldCreate(InitView.attachdownMainPath);
		refreshData();
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		super.onItemClick(parent, view, position, id);
		String filepath = mData.get(position).get("path").toString();
		IOHelp.doOpenFile(AttachManagerView.this, filepath);
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		final int mp = position;
		AlertUtil.showAlertMenu(this, "操作", new String[]{"打开","删除","清空附件","重命名","属性"}, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(which==0)
				{
					String filepath = mData.get(mp).get("path").toString();
					IOHelp.doOpenFile(AttachManagerView.this, filepath);
				}
				else if(which==1)
				{
					File file = new File(mData.get(mp).get("path").toString());
					if (file.exists()) {
						file.delete();
					}
					refreshData();
				}
				else if(which==2)
				{
					AlertDialog ad = new AlertDialog.Builder(getContext())
					.setTitle("属性")
					.setPositiveButton("确定", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							IOHelp.deleteFile(new File(InitView.attachdownMainPath));
							File f = new File(InitView.attachdownMainPath);
							if(!f.exists()){
								f.mkdirs();
							}
							refreshData();
							ToastUtil.toastShort(getContext(), "附件已经全部清空");
						}
					})
					.setNegativeButton("取消", null)
					.setMessage(Html.fromHtml("确定要删除所有附件吗？"))
					.create();
					ad.show();
					
					
				}
				else if(which==3)
				{

					LayoutInflater inflater2 = LayoutInflater.from(AttachManagerView.this);
					LinearLayout ll = (LinearLayout) inflater2.inflate(R.layout.alertinput_editview, null);
					final EditText et = (EditText) ll.findViewById(R.id.ai_et);
					et.setText(mData.get(mp).get("title").toString());
					new AlertDialog.Builder(AttachManagerView.this)
					.setTitle("重命名")
					.setView(ll)
					.setPositiveButton("保存", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

							String path = mData.get(mp).get("path").toString();
							String prefiledir = path.substring(0,path.lastIndexOf("/"));
							File f = new File(mData.get(mp).get("path").toString());
							f.renameTo(new File(prefiledir+"/"+et.getText().toString()));
							refreshData();
						}
					})
					.setNegativeButton("取消", null)
					.create().show();
				
				}
				else if(which==4)
				{
					File f = new File(mData.get(mp).get("path").toString());
					AlertUtil.showFileAttribute(getContext(), f);
				}
			}
		});
		return super.onItemLongClick(parent, view, position, id);
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if(v==ivQuery)
		{
			if(etCondition.getText().toString().length()>0){
				mData = getData(InitView.attachdownMainPath);
				List<Map<String, Object>> mData_search = new ArrayList<Map<String,Object>>();
				for(int i=0;i<mData.size();i++){
					if(mData.get(i).get("title").toString().contains(etCondition.getText().toString())){
						mData_search.add(mData.get(i));
					}
				}
				mData = mData_search;
				LstAdapter adapter = new LstAdapter(AttachManagerView.this);
				lv.setAdapter(adapter);
			}
			else{
				refreshData();
			}
		}
	}

	public void refreshData() {
		
		
		
		mData = getData(InitView.attachdownMainPath);

		Long[] time = new Long[mData.size()];
		for(int i=0;i<mData.size();i++){
			time[i] = (Long) mData.get(i).get("time");
		}

		time = Arithmetic.sort(time);

		List<Map<String, Object>> templist = new ArrayList<Map<String,Object>>();
		for(int i=mData.size()-1;i>=0;i--){
			for(int j=0;j<mData.size();j++){
				if(time[i]==(Long) mData.get(j).get("time")){
					templist.add(mData.get(j));
				}
			}
		}

		mData = templist;
		LstAdapter adapter = new LstAdapter(this);
		lv.setAdapter(adapter);
	}

	private List<Map<String, Object>> getData(String dir) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();

		File file = new File(dir);

		File[] files = file.listFiles();//所有文件夹

		for (File currentFile : files) {
			if(currentFile.isDirectory()){
				File[] subfiles = currentFile.listFiles();
				for(File subfile:subfiles){
					if(!subfile.isDirectory()){
						map = new HashMap<String, Object>();
						map.put("path", subfile.getAbsolutePath());
						map.put("time", subfile.lastModified());
						map.put("title", subfile.getName());
						Long time = subfile.lastModified();
						// 格式化时间字符串
						String timestr = DateFormat.format("yyyy.MM.dd kk:mm:ss", time)
								.toString();
						map.put("info", timestr);
						map.put("icon", R.drawable.img_file_48);
						String hz = subfile.getName();
						if (hz.lastIndexOf(".doc") > -1||hz.lastIndexOf(".docx") > -1) {
							map.put("icon", R.drawable.img_attach_doc);
						} 
						else if (hz.lastIndexOf(".xls") > -1||hz.lastIndexOf(".xlsx") > -1) {
							map.put("icon", R.drawable.img_attach_excel);
						} 
						else if (hz.lastIndexOf(".ppt") > -1) {
							map.put("icon", R.drawable.img_attach_ppt);
						}
						else if(hz.lastIndexOf(".rar") > -1){
							map.put("icon", R.drawable.img_rar_48);
						}
						else if(hz.lastIndexOf(".zip") > -1){
							map.put("icon", R.drawable.img_zip_48);
						}
						else if(hz.lastIndexOf(".jpeg") > -1||hz.lastIndexOf(".jpg")>-1){
							map.put("icon", R.drawable.img_jpg_48);
						}
						else if(hz.lastIndexOf(".png") > -1){
							map.put("icon", R.drawable.img_pngb_48);
						}
						else if(hz.lastIndexOf(".mp3") > -1){
							map.put("icon", R.drawable.img_mp3b_48);
						}
						else if(hz.lastIndexOf(".txt") > -1){
							map.put("icon", R.drawable.img_txt_48);
						}
						else if(hz.lastIndexOf(".pdf") > -1){
							map.put("icon", R.drawable.img_pdf_48);
						}
						else if(hz.lastIndexOf(".html") > -1){
							map.put("icon", R.drawable.img_html_48);
						}

						list.add(map);
					}
				}
			}
		}

		return list;
	}

	class LstAdapter extends BaseAdapter
	{
		private LayoutInflater mInflater;

		public LstAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.lv_attach,
						null);
				holder.iv = (ImageView) convertView
						.findViewById(R.id.lv_attach_iv);
				holder.tv = (TextView) convertView
						.findViewById(R.id.lv_attach_tv);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.iv.setBackgroundResource((Integer) mData.get(position)
					.get("icon"));
			final String fileName = (String) mData.get(position).get("title");
			holder.tv.setText(fileName);
			return convertView;
		}
	}

	public final class ViewHolder {
		public ImageView iv;
		public TextView tv;
	}
}
